package com.neusoft.yiyang.medical.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neusoft.yiyang.common.entity.medical.CheckOrder;
import com.neusoft.yiyang.common.entity.medical.CheckOrderRecord;
import com.neusoft.yiyang.common.enums.OrderStatus;
import com.neusoft.yiyang.medical.mapper.CheckOrderMapper;
import com.neusoft.yiyang.medical.mapper.CheckOrderRecordMapper;
import com.neusoft.yiyang.medical.service.CheckOrderRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.List;

@Service
public class CheckOrderRecordServiceImpl implements CheckOrderRecordService {

    @Autowired
    private CheckOrderRecordMapper checkOrderRecordMapper;

    @Autowired
    private CheckOrderMapper checkOrderMapper;

    @Override
    public void createCheckOrderRecord(CheckOrderRecord checkOrderRecord) {
        CheckOrder checkOrder = checkOrderMapper.selectById(checkOrderRecord.getCheckOrderId());
        int time = checkOrder.getFinishedTimes();
        time++;
        if(time == checkOrder.getTimes()) {
            checkOrder.setStatus(OrderStatus.archived);
        }
        checkOrder.setFinishedTimes(time);
        checkOrderMapper.updateById(checkOrder);
        checkOrderRecordMapper.insert(checkOrderRecord);
    }

    @Override
    public List<CheckOrderRecord> getAllCheckOrderRecords() {
        return checkOrderRecordMapper.selectList(null);
    }

    @Override
    public List<CheckOrderRecord> getCheckOrderRecordsByCustomerId(Integer customerId) {
        return checkOrderRecordMapper.selectListByCustomerId(customerId);
    }

    @Override
    public void updateCheckOrderRecord(CheckOrderRecord checkOrderRecord) {
        checkOrderRecordMapper.updateById(checkOrderRecord);
    }

    @Override
    public void deleteCheckOrderRecord(Integer checkOrderRecordId) {
        CheckOrderRecord checkOrderRecord = checkOrderRecordMapper.selectById(checkOrderRecordId);
        CheckOrder checkOrder = checkOrderMapper.selectById(checkOrderRecord.getCheckOrderId());
        int time = checkOrder.getFinishedTimes();
        if(time == checkOrder.getTimes()) {
            checkOrder.setStatus(OrderStatus.active);
        }
        time--;
        checkOrder.setFinishedTimes(time);
        checkOrderMapper.updateById(checkOrder);
        checkOrderRecordMapper.deleteById(checkOrderRecordId);
    }

    //根据checkOrderId获取执行记录
    @Override
    public List<CheckOrderRecord> getCheckOrderRecordByCheckOrder(Integer checkOrderId) {
        QueryWrapper<CheckOrderRecord> qw = new QueryWrapper<>();
        qw.eq("check_order_id", checkOrderId);
        return checkOrderRecordMapper.selectList(qw);
    }
}
